import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getArticlesAPI, type Article, type ArticleListParams } from '@/apis/article'

export const useArticleStore = defineStore('article', () => {
  // 状态
  const articleList = ref<Article[]>([])
  const currentPage = ref(1)
  const sorter = ref<string | null>('weight_desc')
  const isLoading = ref(false)
  const isFinished = ref(false)
  const pageSize = ref(10)

  // 获取文章列表
  const getArticles = async (params?: Partial<ArticleListParams>) => {
    try {
      isLoading.value = true
      const requestParams = {
        current: currentPage.value,
        sorter: sorter.value,
        pageSize: pageSize.value,
        ...params
      }

      const res = await getArticlesAPI(requestParams)

      if (currentPage.value === 1) {
        // 第一页，替换数据
        articleList.value = res.data.rows
      } else {
        // 后续页，追加数据
        articleList.value.push(...res.data.rows)
      }

      // 更新分页信息
      currentPage.value++
      isFinished.value = currentPage.value > res.data.pageTotal

      return res
    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 刷新文章列表
  const refreshArticles = async () => {
    currentPage.value = 1
    isFinished.value = false
    articleList.value = []
    await getArticles()
  }

  // 切换排序
  const changeSorter = async (newSorter: string | null) => {
    sorter.value = newSorter
    await refreshArticles()
  }

  // 重置状态
  const resetState = () => {
    articleList.value = []
    currentPage.value = 1
    sorter.value = 'weight_desc'
    isLoading.value = false
    isFinished.value = false
  }

  return {
    articleList,
    currentPage,
    sorter,
    isLoading,
    isFinished,
    pageSize,
    getArticles,
    refreshArticles,
    changeSorter,
    resetState
  }
})
